﻿// StatusServer.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//
#include "const.h"
#include <iostream>
#include "configMgr.h"
#include "StatusServiceImpl.h"

void RunServer() {
    auto& config = configMgr::GetInst();
    std::string server_address(config["StatusServer"]["host"] + ":" + config["StatusServer"]["port"]);

    StatusServiceImpl service;
    //监听端口和添加服务
    grpc::ServerBuilder builder;
    builder.AddListeningPort(server_address, grpc::InsecureServerCredentials());
    builder.RegisterService(&service);
    //启动服务器
    std::unique_ptr<grpc::Server> server(builder.BuildAndStart());
    std::cout << "Server Listening on" << server_address << std::endl;

    boost::asio::io_context ioc;
    boost::asio::signal_set signals(ioc, SIGINT, SIGTERM);
    signals.async_wait([&server](const boost::system::error_code& error, int signal_number) {
        if (!error)
        {
            std::cout << "Shut down server" << std::endl;
            server->Shutdown();
        }
        });
    //在线程中运行ioc
    std::thread([&ioc]() {ioc.run();}).detach();
    //等待服务器关闭
    server->Wait();
    ioc.stop();
}
int main()
{
    try {
        RunServer();
    }
    catch(std::exception& e){
        std::cerr << "Error:" << e.what() << std::endl;
        return EXIT_FAILURE;
    }
    return 0;
}

